package org.xiaojl.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.xiaojl.modules.sys.entity.SysUserRole;
import org.xiaojl.modules.sys.mapper.SysUserRoleMapper;
import org.xiaojl.modules.sys.service.SysUserRoleService;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

/**
 * <p>
 * 用户角色 服务实现类
 * </p>
 *
 * @author xiaojl
 * @since 2017-09-11
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {

	@Override
	public void updateUserRole(Long userId, String roleIds) {
		List<SysUserRole> list = this.selectList(new EntityWrapper<SysUserRole>().eq("userId",userId).orderBy("id", true));
		StringBuffer buffer = new StringBuffer("");
		for(SysUserRole r:list){
			buffer.append(r.getRoleId());
			buffer.append(",");
		}
		String rIds = buffer.toString();
		if(rIds.endsWith(",")){
			rIds = rIds.substring(0, rIds.length()-1);
		}
		
		if(!rIds.equals(roleIds)){
			this.delete(new EntityWrapper<SysUserRole>().eq("userId",userId));
			
			String[] roleIdArray = roleIds.split(",");
			if(roleIdArray!=null && roleIdArray.length>0){
				List<SysUserRole> l = new ArrayList<SysUserRole>();
				for(String str : roleIdArray){
					SysUserRole ur = new SysUserRole();
					ur.setUserId(userId);
					ur.setRoleId(Long.valueOf(str));
					
					l.add(ur);
				}
				
				this.insertBatch(l);
			}
		}
		
	}
	
}
